/*
 * @Author: NaturalHulk 2066634567@qq.com
 * @Date: 2024-10-08 09:31:44
 * @LastEditors: NaturalHulk 2066634567@qq.com
 * @LastEditTime: 2024-12-04 11:31:24
 * @FilePath: /xhs-mom-new/src/store/modules/user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { GetNoMessageAPI } from '@/api/layout.js'
const useUserStore = defineStore('user', {
  state: () => ({
    socket: 0,
    msgTotal: 0,
    msgIsShow: false,
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    userId: ''
  }),
  actions: {
    // socket 触发
    changeSocket() {
      this.socket++
    },
    async setMsgTotal(total) {
      const result = await GetNoMessageAPI()
      console.log('执行', result)
      this.msgTotal = Number(result)
    },

    setMsgIsShow(t) {
      this.msgIsShow = t
    },

    // 登录
    login(userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            setToken(res.data.access_token)
            this.token = res.data.access_token
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            const user = res.user
            const avatar = user.avatar == '' || user.avatar == null ? defAva : user.avatar

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = user.userName
            this.userId = user.userId

            this.avatar = avatar
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.userId = ''
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
})

export default useUserStore
